import {getUserInfoByUserDDId} from '@/api/login'
import {anonymousPmProgress} from '@/api/manager'
import {Dimension, DimensionTarget, submitPm} from '@/api/myPerformance'
import {CCard} from '@/components/card'
import RejectProgressDrawer from '@/components/drawer/rejectProgressDrawer'
import ScoreSummarizeModal from '@/components/modal/scoreSummarizeModal'
import {SplitLine} from '@/components/splitLine'
import ProcessSteps from '@/components/steps/processSteps'
import {CnBoldSpan, CnMediumP, CnNormalP, CnNormalSpan} from '@/components/text'
import PmLogTimeLine from '@/components/timeLine/pmLog'
import useCheckPmStatus from '@/hooks/checkPmStatus'
import useModal from '@/hooks/modalHook'
import useLog from '@/hooks/pm/log'
import useMyPm from '@/hooks/pm/myPm'
import useProgress from '@/hooks/pm/progress'
import {useTableLoading} from '@/hooks/tableHook'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import deepClone from '@/libs/deepClone'
import {getDDUsers} from '@/libs/dingding'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {checkIsPhone, isNull, unReplaceBreak, zeroize} from '@/libs/toolkit'
import router from '@/router'
import {computed, defineComponent, onMounted, PropType, reactive, watch} from 'vue'
import {BtnsByProgressStep} from './components/btnsByProgressStep'
import PhomePmBaseInfo from './phonePmBaseInfo'
const {message} = ant_design_vue

/**
 * 当前绩效所属人员与登录人员一致时
 */

export namespace PmBaseInfoProps {
  /**
   * @checkInfo 员工绩效档案
   * @myPm 我的绩效
   * @targetConfirm 目标确认
   * @selfAssessment 自评
   * @leaderAssessment 主管评分
   */
  export type Type =
    | 'checkInfo'
    | 'myPm'
    | 'targetConfirm'
    | 'targetBySelf'
    | 'targetByLeader'
    | 'scoreBySelf'
    | 'scoreByLeader'
}

const PmBaseInfo = defineComponent({
  props: {
    type: {
      type: String as PropType<PmBaseInfoProps.Type>
    },
    /** 当前绩效所属人员 */
    userDDId: {
      type: String,
      required: true
    },
    defaultPmId: Number
  },
  setup(props, ctx) {
    const {store} = useGlobalAPI()

    const {startLoading, closeLoading, loading} = useTableLoading()

    const {
      getMyPmListByUserDDId,
      myPmList,
      getPmDataByPmId,
      pmDataList,
      targetWeightCountByPmDataList,
      dimensionWeightCountByPmDataList
    } = useMyPm()

    const {
      pmProgress,
      getPmProgress,
      nowRunning,
      nowRunningByLoginuser,
      allScoreLeader,
      allScoreSelf,
      scoreLeaderByLoginUser,
      appointByLoginUser,
      allAppoint
    } = useProgress()

    const {
      visible: scoreSummarizeVisible,
      openModal: openScoreSummarizeModel,
      closeModal: closeScoreSummarize
    } = useModal()

    const {
      startLoading: startCardLoading,
      closeLoading: closeCardLoading,
      loading: cardLoading
    } = useTableLoading()

    const isPhone = computed(() => checkIsPhone())

    let state = reactive<{
      currentPmId: number | undefined
      dataSource: MyPm.TableData[]
      /**当前绩效所属用户 */
      owner: User.Info | null

      rejectProgressDrawerVisible: boolean
      mamgerRejectProgressDrawerVisible: boolean
    }>({
      dataSource: [],
      currentPmId: undefined,
      owner: null,
      rejectProgressDrawerVisible: false,
      mamgerRejectProgressDrawerVisible: false
    })

    /**是否加载绩效下拉选择框 */
    const isLoadMyPmList = computed(() => ['myPm', 'checkInfo'].includes(props.type || ''))

    /**登陆者信息 */
    const loginUserInfo = computed(() => store.getters['dingding/ddUserInfo'])

    /**表格头 */
    const tableColumns = computed<CColumn<MyPm.TableData>[]>(() => {
      const defaultCustomRender = (data: CBodyCell<MyPm.TableData>) => (
        <a-tooltip title={data.text}>
          <CnNormalSpan
            class='w-full p-16'
            style={{
              color: '#606266',
              whiteSpace: 'break-spaces',
              display: 'inline-block',
              width: data.column.width + 'px',
              fontSize: '12px'
            }}
          >
            {data.text}
            {data.column.dataIndex === 'pmTargetName' ? (
              data.record.isBonus === 1 ? (
                <CnNormalSpan class='text-primary'>（加分项）</CnNormalSpan>
              ) : null
            ) : null}
          </CnNormalSpan>
        </a-tooltip>
      )

      function customCell(data: MyPm.TableData) {
        if (data.pmDimensionId === -1 && nowRunning.value?.[0].pmStageCode !== '0019') {
          return {
            rowSpan: 0,
            colSpan: 0
          }
        }
        return {}
      }

      let columns: CColumn<MyPm.TableData>[] = [
        {
          title: '维度',
          dataIndex: 'pmDimensionName',
          align: 'center',
          width: 100,
          customCell(data, index) {
            if (!pmDataList.value) return {}
            if (data.pmDimensionId === -1 && nowRunning.value?.[0].pmStageCode !== '0019') {
              return {
                rowSpan: 0,
                colSpan: 0
              }
            }

            // 当前指标所在维度在dataSource中的第一个下标
            const firstDimenstionIdIdx =
              state.dataSource?.findIndex(
                (item, idx) => item.pmDimensionId === data.pmDimensionId
              ) || 0

            // 当前指标所在维度共有多少指标
            const targetCountByDimenstionId =
              state.dataSource?.filter((item, idx) => item.pmDimensionId === data.pmDimensionId)
                .length || 1

            /**默认跨0行*/
            const rowSpan: number = index === firstDimenstionIdIdx ? targetCountByDimenstionId : 0

            return rowSpan
              ? {
                  rowSpan
                }
              : {
                  rowSpan: 0,
                  colSpan: 0
                }
          },
          customRender({record, text, column}) {
            if (record.pmDimensionId === -1) {
              return (
                <CnNormalP
                  class='p-16'
                  style={{
                    color: '#606266',
                    whiteSpace: 'normal',
                    wordBreak: 'break-word',
                    display: 'inline-block',
                    width: column.width + 'px',
                    fontSize: '12px'
                  }}
                >
                  {text}
                </CnNormalP>
              )
            } else {
              return [
                <div class='p-16'>
                  <CnNormalP
                    style={{
                      color: '#606266',
                      whiteSpace: 'normal',
                      wordBreak: 'break-word',
                      display: 'inline-block',
                      width: column.width + 'px',
                      fontSize: '12px'
                    }}
                  >
                    {text}
                  </CnNormalP>
                  <br />
                  <CnNormalP
                    style={{
                      color: '#606266',
                      whiteSpace: 'normal',
                      wordBreak: 'break-word',
                      display: 'inline-block',
                      width: column.width + 'px',
                      fontSize: '12px'
                    }}
                  >
                    {`(${record.pmDimensionWeight}%)`}
                  </CnNormalP>
                </div>
              ]
            }
          }
        },
        {
          title: '指标名称',
          dataIndex: 'pmTargetName',
          customCell: customCell,
          width: 180,
          customRender(data) {
            return defaultCustomRender(data)
          }
        },
        {
          title: '考核标准',
          dataIndex: 'pmTargetStand',
          maxWidth: 900,
          customCell: customCell,
          customRender(data) {
            data.text = JSON.parse(JSON.stringify(unReplaceBreak(data.text)))
            return defaultCustomRender(data)
          }
        },
        {
          title: '权重(%)',
          dataIndex: 'pmTargetWeight',
          width: 80,
          align: 'center',
          customCell: customCell,
          customRender(data) {
            return defaultCustomRender(data)
          }
        }
      ]

      if ((nowRunning.value?.[0].pmProgressStep || 0) >= 4) {
        // 根据自评人数动态添加自评栏
        const selfCheckColumns: CColumn<MyPm.TableData>[] = allScoreSelf.value.map((item, idx) => ({
          title: `自评:${item.makeUserName}`,
          children: [
            {
              title: '评分',
              dataIndex: ['scoreSelfCheckList', idx + '', 'score'],
              align: 'center',
              width: 80,
              customCell: customCell,
              customRender(data) {
                data.text = zeroize(data.text, 2, true)
                return defaultCustomRender(data)
              }
            },
            {
              title: '说明',
              dataIndex: ['scoreSelfCheckList', idx + '', 'scoreContent'],
              customCell: customCell,
              customRender(data) {
                data.text = JSON.parse(JSON.stringify(unReplaceBreak(data.text)))
                return defaultCustomRender(data)
              }
            }
          ]
        }))
        columns.push(...selfCheckColumns)
      }

      if ((nowRunning.value?.[0].pmProgressStep || 0) >= 6) {
        // 根据主管评分人数动态添加自评栏
        const leaderCheckColumns: CColumn<MyPm.TableData>[] = allScoreLeader.value.map(
          (item, idx) => ({
            title: `主管评分:${item.makeUserName}(${item.scoreWeight}%)`,
            children: [
              {
                title: '评分',
                dataIndex: ['leaderCheckList', idx + '', 'score'],
                align: 'center',
                width: 80,
                customCell: customCell,
                customRender(data) {
                  let currentLeaderCheck = data.record.leaderCheckList?.find(
                    leaderCheck => item.makeUserDDId === leaderCheck?.makeUserDDId
                  )
                  data.text = currentLeaderCheck ? zeroize(currentLeaderCheck.score, 2, true) : ''
                  return defaultCustomRender(data)
                }
              },
              {
                title: '说明',
                dataIndex: ['leaderCheckList', idx + '', 'scoreContent'],
                customCell: customCell,
                customRender(data) {
                  let currentLeaderCheck = data.record.leaderCheckList?.find(
                    leaderCheck => item.makeUserDDId === leaderCheck?.makeUserDDId
                  )

                  data.text = currentLeaderCheck
                    ? JSON.parse(JSON.stringify(unReplaceBreak(currentLeaderCheck.scoreContent)))
                    : ''

                  return defaultCustomRender(data)
                }
              }
            ]
          })
        )

        columns.push(...leaderCheckColumns)
      }

      /**当存在指定评分人，且流程长度大于7时 */
      if ((nowRunning.value?.[0].pmProgressStep || 0) >= 7 && allAppoint.value.length) {
        // 根据主管评分人数动态添加自评栏
        const appointCheckColumns: CColumn<MyPm.TableData>[] = allAppoint.value.map((item, idx) => {
          return {
            title: `指定人员评分:${item.makeUserName}(${item.scoreWeight}%)`,
            children: [
              {
                title: '评分',
                dataIndex: ['appointCheckList', idx + '', 'score'],
                align: 'center',
                width: 80,
                customCell: customCell,
                customRender(data) {
                  let currentAppointCheck = data.record.appointCheckList?.find(
                    appointCheck => item.makeUserDDId === appointCheck?.makeUserDDId
                  )
                  data.text = currentAppointCheck ? zeroize(currentAppointCheck.score, 2, true) : ''
                  return defaultCustomRender(data)
                }
              },
              {
                title: '说明',
                dataIndex: ['appointCheckList', idx + '', 'scoreContent'],
                customCell: customCell,
                customRender(data) {
                  let currentAppointCheck = data.record.appointCheckList?.find(
                    appointCheck => item.makeUserDDId === appointCheck?.makeUserDDId
                  )

                  data.text = currentAppointCheck
                    ? JSON.parse(JSON.stringify(unReplaceBreak(currentAppointCheck.scoreContent)))
                    : ''

                  return defaultCustomRender(data)
                }
              }
            ]
          }
        })
        columns.push(...appointCheckColumns)
      }

      // 根据流程步骤，判断是否展示考核结果以及绩效等级
      if (nowRunning.value?.[0].pmStageCode === '0019') {
        columns.push(
          {
            title: '考核结果',
            dataIndex: 'pmScore',
            align: 'center',
            customCell: (data, index) => {
              customCell(data)
              return index === 0
                ? {
                    rowSpan: state.dataSource.length
                  }
                : {
                    rowSpan: 0,
                    colSpan: 0
                  }
            },
            customRender(data) {
              data.text = zeroize(data.text, 2, true)

              return defaultCustomRender(data)
            }
          },
          {
            title: '绩效等级',
            align: 'center',
            dataIndex: 'pmScoreLevel',
            customCell: (data, index) => {
              customCell(data)
              return index === 0
                ? {
                    rowSpan: state.dataSource.length
                  }
                : {
                    rowSpan: 0,
                    colSpan: 0
                  }
            },
            customRender(data) {
              return defaultCustomRender(data)
            }
          }
        )
      }

      console.log('当前表格头', columns)

      return columns
    })

    /**下拉选择绩效options */
    const myPmSelectOptions = computed<{label: string; value: number}[]>(
      () =>
        myPmList.value.map(item => ({
          label: item.pmFormName,
          value: item.pmId
        })) || []
    )

    /**当前绩效 */
    const currentMyPm = computed(() =>
      myPmList.value?.find(item => item.pmId === state.currentPmId)
    )

    /**用户在当前绩效中，所属考评组 */
    const currentGroupId = computed(() => currentMyPm.value?.pmGroupId)

    /**监听当前绩效指标Id变化 */
    watch(
      () => state.currentPmId,
      (n, o) => {
        if (!isNull(n)) {
          getMyPmList()
        }
      }
    )

    /**监听传入的用户Id，并根据Id获取用户信息 */
    watch(
      () => props.userDDId,
      n => {
        n && getOwnerInfo()
      },
      {immediate: true}
    )

    // /**获取指定用户的绩效列表 */
    function getMyPmList() {
      getMyPmListByUserDDId({
        userDDId: props.userDDId,
        updateMyPmList: true,
        success: data => {
          console.log('---------------------', data)

          if (!props.defaultPmId && !state.currentPmId) {
            state.currentPmId = data[0].pmId
          }

          if (props.defaultPmId && !state.currentPmId) {
            state.currentPmId = props.defaultPmId
          }

          console.log(myPmList.value, state.currentPmId)

          state.currentPmId &&
            getPmProgress({
              pmId: state.currentPmId,
              updatePmProgress: true,
              success: data => {
                getTableData()
              }
            })
        }
      })
    }

    function getTableData() {
      if (!state.currentPmId) return
      startLoading()
      getPmDataByPmId({
        pmId: state.currentPmId,
        updatePmData: true,
        success: data => {
          if (data && data.length === 0) {
            state.dataSource = []
          } else {
            try {
              let tableData: MyPm.TableData[] = []

              let customScoreSelfCheckList: MyPm.ScoreSelfCheck[] = deepClone(
                data[0].pmTargetList[0].scoreSelfCheckList || []
              )

              for (let i = 0; i < customScoreSelfCheckList.length; i++) {
                const customScoreSelfCheck = customScoreSelfCheckList[i]
                if (!customScoreSelfCheck) {
                  customScoreSelfCheckList.splice(i, 1)
                  continue
                }
                customScoreSelfCheck.score = 0
                customScoreSelfCheck.scoreContent = ''
              }

              let customLeaderCheckList: MyPm.LeaderCheck[] = []
              console.log('所有主管', allScoreLeader.value)
              for (let i = 0; i < allScoreLeader.value.length; i++) {
                let leader = allScoreLeader.value[i]
                customLeaderCheckList[i] = {
                  pmTargetCheckId: -1,
                  makeUserDDId: leader.makeUserDDId,
                  makeUserName: leader.makeUserName,
                  pmTargetId: -1,
                  pmProgressId: -1,
                  score: 0,
                  scoreContent: '',
                  scoreDesc: '',
                  scoreWeight: leader.scoreWeight
                }
              }

              let customAppointCheckList: MyPm.LeaderCheck[] = []
              console.log('所有指定评分人', allAppoint.value)
              for (let i = 0; i < allAppoint.value.length; i++) {
                let appoint = allAppoint.value[i]
                customAppointCheckList[i] = {
                  pmTargetCheckId: -1,
                  makeUserDDId: appoint.makeUserDDId,
                  makeUserName: appoint.makeUserName,
                  pmTargetId: -1,
                  pmProgressId: -1,
                  score: 0,
                  scoreContent: '',
                  scoreDesc: '',
                  scoreWeight: appoint.scoreWeight
                }
              }

              for (let i = 0; i < data.length; i++) {
                const dimension = data[i]
                for (let ii = 0; ii < dimension.pmTargetList.length; ii++) {
                  const pmTarget = dimension.pmTargetList[ii]

                  //? 判断指标是否能展示给评分人 -----------------------------------
                  /**当前登陆者不是该绩效所属人时 */
                  if (
                    props.userDDId !== loginUserInfo.value.userId &&
                    (nowRunning.value?.[0].pmProgressStep || 0) > 5
                  ) {
                    // 当前登陆者是主管评分人,且目标评分人有人时
                    if (scoreLeaderByLoginUser.value && pmTarget.appointUserDDId) {
                      continue
                    } else if (
                      appointByLoginUser.value &&
                      pmTarget.appointUserDDId !== appointByLoginUser.value.makeUserDDId
                    ) {
                      // 当前登陆者是目标指定评分人,且该目标的指定评分人不是当前登陆者时
                      continue
                    } else {
                      // 都不是的时候，当前登陆者就是管理员
                    }
                  }

                  tableData.push({
                    pmDimensionId: dimension.pmDimensionId,
                    pmId: dimension.pmId,
                    pmDimensionName: dimension.pmDimensionName,
                    pmDimensionTypeCode: dimension.pmDimensionTypeCode,
                    pmDimensionWeight: dimension.pmDimensionWeight,
                    pmDimensionIsCustomSelf: dimension.isCustomSelf,
                    pmDimensionIsImport: dimension.isImport,
                    pmTargetId: pmTarget.pmTargetId,
                    pmTargetName: pmTarget.pmTargetName,
                    pmTargetStand: pmTarget.pmTargetStand,
                    pmTargetWeight: pmTarget.pmTargetWeight,
                    scoreSelfCheckList: pmTarget.scoreSelfCheckList || [],
                    leaderCheckList: pmTarget.leaderCheckList || [],
                    appointCheckList: pmTarget.appointCheckList || [],
                    pmScore: currentMyPm.value?.pmScore,
                    pmScoreLevel: currentMyPm.value?.pmScoreLevel,
                    isBonus: pmTarget.isBonus,
                    isMustSelect: pmTarget.isMustSelect,
                    pmTargetRange: pmTarget.pmTargetRange,
                    appointScoreSign: pmTarget.appointScoreSign,
                    appointUserDDId: pmTarget.appointUserDDId
                  })

                  for (let iii = 0; iii < (pmTarget.scoreSelfCheckList || []).length; iii++) {
                    const scoreSelfCheck = (pmTarget.scoreSelfCheckList || [])[iii]
                    for (let iiii = 0; iiii < customScoreSelfCheckList.length; iiii++) {
                      const customScoreSelfCheck = customScoreSelfCheckList[iiii]

                      if (customScoreSelfCheck.makeUserDDId === scoreSelfCheck?.makeUserDDId) {
                        customScoreSelfCheck.score +=
                          pmTarget.isBonus === 0
                            ? scoreSelfCheck.score * (pmTarget.pmTargetWeight / 100)
                            : scoreSelfCheck.score
                      }
                    }
                  }

                  for (let iii = 0; iii < (pmTarget.leaderCheckList || []).length; iii++) {
                    const leaderCheck = (pmTarget.leaderCheckList || [])[iii]
                    for (let iiii = 0; iiii < customLeaderCheckList.length; iiii++) {
                      const customLeaderCheck = customLeaderCheckList[iiii]
                      if (
                        leaderCheck &&
                        customLeaderCheck &&
                        customLeaderCheck.makeUserDDId === leaderCheck.makeUserDDId
                      ) {
                        customLeaderCheck.score +=
                          pmTarget.isBonus === 0
                            ? leaderCheck.score *
                              (pmTarget.pmTargetWeight / 100) *
                              (leaderCheck.scoreWeight / 100)
                            : leaderCheck.score * (leaderCheck.scoreWeight / 100)
                      }
                    }
                  }

                  for (let iii = 0; iii < (pmTarget.appointCheckList || []).length; iii++) {
                    const appointCheck = (pmTarget.appointCheckList || [])[iii]
                    for (let iiii = 0; iiii < customAppointCheckList.length; iiii++) {
                      const customAppointCheck = customAppointCheckList[iiii]
                      if (
                        appointCheck &&
                        customAppointCheck &&
                        customAppointCheck.makeUserDDId === appointCheck.makeUserDDId
                      ) {
                        customAppointCheck.score +=
                          appointCheck.score *
                          (pmTarget.pmTargetWeight / 100) *
                          (appointCheck.scoreWeight / 100)
                      }
                    }
                  }
                }
              }

              let pmStageCode = Array.from(
                new Set(nowRunning.value?.map(item => item.pmStageCode))
              )[0]

              if (pmStageCode === '0019') {
                tableData.push({
                  pmDimensionId: -1,
                  pmId: -1,
                  pmDimensionName: '总分',
                  pmDimensionTypeCode: '0020',
                  pmDimensionWeight: 0,
                  pmDimensionIsCustomSelf: 0,
                  pmDimensionIsImport: 0,
                  pmTargetId: -1,
                  pmTargetName: '',
                  pmTargetStand: '',
                  pmTargetWeight: eval(
                    tableData
                      .filter(item => item.isBonus !== 1)
                      .map(item => item.pmTargetWeight)
                      .join('+')
                  ),
                  scoreSelfCheckList: customScoreSelfCheckList,
                  leaderCheckList: customLeaderCheckList,
                  appointCheckList: customAppointCheckList,
                  pmScore: Array.from(new Set(tableData.map(dimen => dimen.pmTargetWeight)))[0],
                  pmScoreLevel: undefined,
                  isBonus: 0,
                  isMustSelect: 0,
                  pmTargetRange: '',
                  appointScoreSign: 0,
                  appointUserDDId: undefined
                })
              }

              console.log('组合好后的表格数据', tableData)
              state.dataSource = tableData
            } catch (err) {
              console.log('catch')

              state.dataSource = []
              console.error(err)
            }
          }
          closeLoading()
        },
        error: () => {
          state.dataSource = []
          console.log('error')
          closeLoading()
        }
      })
    }

    /**根据props.userDDId查询当前绩效所属用户信息 */
    function getOwnerInfo() {
      getUserInfoByUserDDId({userDDId: props.userDDId})
        .then(res => {
          state.owner = res.data
          console.log('当前绩效所属用户信息', res.data)
        })
        .catch(err => {})
    }

    function getPageData() {
      getMyPmList()
    }

    function combDimensionBypmDataList() {
      let dimension = (pmDataList.value || []).map<Dimension>(dimension => ({
        pmDimensionId: dimension.pmDimensionId,
        pmDimensionName: dimension.pmDimensionName,
        pmDimensionTypeCode: dimension.pmDimensionTypeCode,
        pmDimensionWeight: dimension.pmDimensionWeight,
        isCustomSelf: dimension.isCustomSelf,
        isImport: dimension.isImport,
        sort: dimension.sort,
        pmTargetList: dimension.pmTargetList.map<DimensionTarget>(target => ({
          isBonus: target.isBonus,
          pmTargetRange: target.pmTargetRange,
          pmTargetId: target.pmTargetId,
          appointScoreSign: target.appointScoreSign,
          appointUserDDId: target.appointUserDDId,
          makeProperty: undefined,
          pmTargetName: target.pmTargetName,
          pmTargetStand: target.pmTargetStand,
          pmTargetWeight: target.pmTargetWeight,
          sort: target.sort,
          isMustSelect: target.isMustSelect,
          pmDimensionId: target.pmDimensionId
        }))
      }))

      const dimenAndTarget = dimension.map(dimen => ({
        dimenName: dimen.pmDimensionName,
        dimenWeight: dimen.pmDimensionWeight,
        targetWight: eval(
          dimen.pmTargetList.map(target => target.pmTargetWeight).join('+')
        ) as number
      }))

      for (let i = 0; i < dimenAndTarget.length; i++) {
        const val = dimenAndTarget[i]
        console.log('提交权重', val.dimenWeight)

        if (val.dimenWeight === undefined) {
          message.warning(`维度：${val.dimenName}，有指标未指定权重`)
        } else if (val.dimenWeight > val.targetWight) {
          message.warning(`维度：${val.dimenName}，所有指标的权重大于${val.dimenWeight}`)
          return false
        } else if (val.dimenWeight > val.targetWight) {
          message.warning(`维度：${val.dimenName}，所有指标的权重小于${val.dimenWeight}`)
          return false
        }
      }

      if (!dimension.length) {
        message.warning(`请先制定目标！`)
        return false
      }
      return dimension
    }

    /**保存点击 */
    function handleSubmitClick() {
      if (targetWeightCountByPmDataList.value !== dimensionWeightCountByPmDataList.value) {
        message.warning(`所有指标权重未达到${dimensionWeightCountByPmDataList.value}`)
        return
      }

      if (!nowRunning.value) return

      if (nowRunning.value && nowRunning.value.length) {
        // 四步之后，八步之前，属于驳回流程后，旧评分还在，点击评分时进入这里
        if (nowRunning.value[0].pmProgressStep >= 4 && nowRunning.value[0].pmProgressStep < 8) {
          let dimen = combDimensionBypmDataList()
          if (!dimen) return
          openScoreSummarizeModel()
        } else {
          // 目标制定，或者目标确认
          handleScoreSummarizeConfirm('')
        }
      }
    }

    function handleScoreSummarizeConfirm(scoreSummary?: string) {
      if (!nowRunningByLoginuser.value) return

      let dimen = combDimensionBypmDataList()

      if (!dimen) return

      startCardLoading()

      submitPm({
        pmProgressId: nowRunningByLoginuser.value.pmProgressId,
        data: dimen,
        scoreSummary: scoreSummary || undefined
      })
        .then(res => {
          closeCardLoading()
          // router.push('/')
          location.reload()
        })
        .catch(err => {
          closeCardLoading()
        })
    }

    /**处理管理员点击驳回 */
    function handleManagerRebutClick() {
      state.mamgerRejectProgressDrawerVisible = true
    }

    /**点击驳回 */
    function handlePmTurnOver() {
      getDDUsers({multiple: false, max: 1})
        .then(res => {
          if (res !== 'cancel') {
            if (Array.isArray(res) && res.length) {
              if (nowRunning.value && nowRunning.value.length && nowRunning.value[0].pmProgressId) {
                anonymousPmProgress({
                  userDDId: loginUserInfo.value.userId,
                  anonymousUserDDId: res[0].emplId,
                  nowPmProgressId: nowRunning.value[0].pmProgressId
                })
                  .then(res => {
                    router.back()
                  })
                  .catch(err => {})
              } else {
                message.warning('转交时，流程信息缺失！')
              }
            } else {
              message.warning('转交人选择失败，请重新选择！')
            }
          }
        })
        .catch(err => {})
    }

    onMounted(() => {
      getPageData()
    })

    return () =>
      !isPhone.value ? (
        <CCard
          loading={cardLoading.value}
          title='我的绩效'
          showTitle={false}
          class='p-24 CBC-bg-toRight'
        >
          {/* header */}
          <div class=' flex justify-between items-center '>
            <div class='flex items-center gap-x-47'>
              <span class='flex items-center gap-x-10'>
                {/* user-header */}
                <span class='bg-black rounded-4 overflow-hidden'>
                  <img src={state.owner?.avatar || ''} class='w-34 h-34'></img>
                </span>
                {/* user-msg */}
                <span>
                  <CnNormalP class='text-12'>{state.owner?.userName}</CnNormalP>
                  <CnNormalP class='text-12'>{state.owner?.deptName}</CnNormalP>
                </span>
              </span>

              <span class=''>
                {/* select-pmBymonth */}
                {isLoadMyPmList.value && myPmSelectOptions.value.length ? (
                  <a-select
                    v-model={[state.currentPmId, 'value']}
                    size='mini'
                    class='w-215'
                    options={myPmSelectOptions.value}
                  ></a-select>
                ) : null}
              </span>
            </div>

            <div class='flex items-center gap-x-8'>
              {state.owner && currentMyPm.value && currentMyPm.value?.status === 1 ? (
                <BtnsByProgressStep
                  groupId={currentGroupId.value}
                  nowRunningByLoginuser={nowRunningByLoginuser.value}
                  nowRunningProgress={nowRunning.value}
                  owner={state.owner}
                  ownerPm={currentMyPm.value}
                  onRejectProgress={() => {
                    state.rejectProgressDrawerVisible = true
                  }}
                  onTargetConfirm={handleSubmitClick}
                  onLeaderTargetConfirm={handleSubmitClick}
                  onPmTurnover={handlePmTurnOver}
                ></BtnsByProgressStep>
              ) : null}

              {currentMyPm.value?.status === 0 ? (
                <CnBoldSpan class='text-danger text-20'>已撤销</CnBoldSpan>
              ) : (
                ''
              )}
            </div>
          </div>
          {/* splitLine */}
          <div class='py-20 '>
            <SplitLine class='w-full h-1 p-0'></SplitLine>
          </div>
          {/* process */}
          <div class='w-1/2 mx-auto'>
            <ProcessSteps data={pmProgress.value} now={nowRunning.value}></ProcessSteps>
          </div>

          {/* processMstTable */}
          {!pmDataList.value ? (
            <a-empty description='暂无数据'></a-empty>
          ) : !pmDataList.value.length ? (
            <a-empty description='请先制定绩效目标'></a-empty>
          ) : (
            <a-table
              class='custom-table'
              loading={loading.value}
              pagination={false}
              columns={tableColumns.value}
              data-source={state.dataSource}
              scroll={{x: 'max-content'}}
              bordered
            ></a-table>
          )}

          {state.currentPmId ? <PmLogTimeLine pmId={state.currentPmId}></PmLogTimeLine> : null}
          {state.rejectProgressDrawerVisible ? (
            <RejectProgressDrawer
              v-model={[state.rejectProgressDrawerVisible, 'visible']}
              rejectNowPmProgressId={nowRunning.value?.[0]?.pmProgressId}
            ></RejectProgressDrawer>
          ) : null}
          <ScoreSummarizeModal
            v-models={[[scoreSummarizeVisible.value, 'visible']]}
            onConfirm={handleScoreSummarizeConfirm}
          ></ScoreSummarizeModal>
        </CCard>
      ) : state.owner && currentMyPm.value && currentGroupId.value ? (
        <div>
          <PhomePmBaseInfo
            owner={state.owner}
            ownerPm={currentMyPm.value}
            pmProgress={pmProgress.value}
            pmData={state.dataSource}
            nowRunningByLoginuser={nowRunningByLoginuser.value}
            nowRunningProgress={nowRunning.value}
            groupId={currentGroupId.value}
            onRejectProgress={() => {
              state.rejectProgressDrawerVisible = true
            }}
            onTargetConfirm={handleSubmitClick}
            onLeaderTargetConfirm={handleSubmitClick}
            onPmTurnover={handlePmTurnOver}
          ></PhomePmBaseInfo>
          {state.rejectProgressDrawerVisible ? (
            <RejectProgressDrawer
              v-model={[state.rejectProgressDrawerVisible, 'visible']}
              rejectNowPmProgressId={nowRunning.value?.[0]?.pmProgressId}
            ></RejectProgressDrawer>
          ) : null}
        </div>
      ) : (
        <div></div>
      )
  }
})

export default PmBaseInfo
